// 广播动作  
const scanAction = 'com.android.server.scannerservice.broadcast';
// 广播标签 
const scanExtra = 'scannerdata';
class Broadcast {
	constructor(obj) {
		this.action = scanAction;
		this.extra = scanExtra;
		this.plus = obj.plus;
		this.main = this.plus.android.runtimeMainActivity();
		const IntentFilter = this.plus.android.importClass('android.content.IntentFilter');
		this.filter = new IntentFilter();
		this.receiver = null;
		this.initScan();
	}
	// 初始化广播
	initScan() {
		const _this = this;
		this.filter.addAction(this.action);
		this.receiver = this.plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver',{  
		onReceive: function(context, intent) {  
			_this.plus.android.importClass(intent);
			// 提交事件
			uni.$emit('scan-result', intent.getStringExtra(_this.extra));
		}});   
	}
	// 开始扫码
	startScan() {
		if (!this.receiver) {
			this.initScan();
		}
		this.main.registerReceiver(this.receiver, this.filter);  
	}
	// 结束扫码
	stopScan() {
		this.main.unregisterReceiver(this.receiver);   
	}
	// 清除事件
	off() {
		uni.$off('scan-result');
	}
	endScan() {
		this.stopScan();
		this.off();
	}
}

export default Broadcast;